package com.wdb007.venus.wss.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wdb007.venus.svc.facade.ProcessInstructionService;
import com.wdb007.venus.svc.facade.process.model.ProcessInstructionLogDTO;
import com.wdb007.venus.wss.channelgroup.BookCaseChannelGroups;
import com.wdb007.venus.wss.constants.PushActionEnum;
import com.wdb007.venus.wss.service.WebSocketServerService;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
@Service("bookGridReqService")
@Sharable
@Scope("prototype")
public class BookGridReqService implements WebSocketServerService {

	private static Logger logger = LoggerFactory.getLogger(BookGridReqService.class);
	
	@Autowired
	private ProcessInstructionService processInstructionService;
	
	@Override
	public String doService(ChannelHandlerContext ctx, String request) throws Exception {
		
		JSONObject jsonObj = JSON.parseObject(request);
		String bookCaseId = jsonObj.getString("bookCaseId");
		String bookGridId = jsonObj.getString("bookGridId");
		String pushId = "";
		ProcessInstructionLogDTO pi = new ProcessInstructionLogDTO();
		if(PushActionEnum.bookgrid_unlock_req.name().equals(jsonObj.get("action"))) {
			pi.setContent(jsonObj.toJSONString());
			pi.setBookgridCode(bookGridId);
			pushId = processInstructionService.unlockReqFromAppServer(pi) +"";
		}else if(PushActionEnum.bookgrid_status_req.name().equals(jsonObj.get("action"))) {
			pi.setContent(jsonObj.toJSONString());
			pi.setBookgridCode(bookGridId);
			pi.setInstructionGroupId(Long.valueOf(jsonObj.getString("pushId")));
			pushId = processInstructionService.statusReqFromAppServer(pi) + "";
		}else if(PushActionEnum.bookgrid_check_req.name().equals(jsonObj.get("action"))) {
			pi.setContent(jsonObj.toJSONString());
			pi.setBookgridCode(bookGridId);
			pushId = jsonObj.getString("pushId");
			if(null != pushId && !"".equals(pushId)) {
				pi.setInstructionGroupId(Long.valueOf(jsonObj.getString("pushId")));
			}
			pushId = processInstructionService.checkReqFromAppServer(pi) + "";
		}
		jsonObj.remove("bookCaseId");
		jsonObj.put("pushId", pushId+"");
		logger.info("debug {} : 给机柜书格[{}],下发内容[{}]",jsonObj.getString("action"), bookGridId, jsonObj.toJSONString());
		BookCaseChannelGroups.broadcast(bookCaseId, jsonObj.toJSONString());
		return null;
	}

}
